package com.aliyun.oss.sdk;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class OSSUtils {

    /**
     * 上传文件
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @param fileName  matchId/aa.jpg
     * @param fileBytes
     * @param publicFlag  bucket默认私有 true 公共读   false  私有读    除了apk下载都用私有访问，防止被别人猜测扫库
     */
            public static PutObjectResult putOSS(String endpoint,
                                             String accessKeyId,
                                             String accessKeySecret,
                                             String bucketName ,
                                             String fileName,
                                             byte[] fileBytes,
                                             Boolean  publicFlag  ){

            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            PutObjectResult objectResult=  ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(fileBytes));
            if(publicFlag){
                ossClient.setObjectAcl(bucketName,fileName, CannedAccessControlList.PublicRead);
            }

            // 关闭OSSClient。
            ossClient.shutdown();
            return  objectResult;
        }


    /**
     * 上传文件 私有独写
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @param fileName  matchId/aa.jpg
     * @param fileBytes
     */
    public static void putOSSPrivate(String endpoint,
                              String accessKeyId,
                              String accessKeySecret,
                              String bucketName ,
                              String fileName,
                              byte[] fileBytes){

        putOSS(endpoint,accessKeyId,accessKeySecret,bucketName,fileName,fileBytes,false);
    }


    /**
     * 返回文件
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @param fileName
     * @return
     * @throws Exception
     */
    public static InputStream  getOSSInputStream(String endpoint,
                              String accessKeyId,
                              String accessKeySecret,
                              String bucketName ,
                              String fileName) throws Exception {

        InputStream inputStream = null;
        ByteArrayOutputStream out =  new ByteArrayOutputStream();

        try{


            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            OSSObject ossObject = ossClient.getObject(bucketName, fileName);

            InputStream  ossIn = ossObject.getObjectContent();
            /**
             * 为什么不直接返回 ossIn
             * 因为 ossObject.close()后 ossIn也将会关闭
             * 造成其他调用此方法的线程 在使用ossIn的时候
             * 获取到的是一个已经被关闭的流
             * inputStream 应该在调用者线程中关闭
             */

            if(ossIn!=null){
                byte[] bts = new byte[1024];
                int len = -1;
                while((len=ossIn.read(bts))!=-1){
                    out.write(bts,0,len);
                }
            }

            byte[] bytes =  out.toByteArray();

            // 关闭OSSClient。
            ossObject.close();
            ossClient.shutdown();

            inputStream =  new ByteArrayInputStream(bytes);

        }catch (Exception e){

            e.printStackTrace();
        }finally {
            if(out!=null){
                out.flush();
                out.close();
            }
        }

        return  inputStream;

    }


    public static byte[]  getOSSBytes(String endpoint,
                                          String accessKeyId,
                                          String accessKeySecret,
                                          String bucketName ,
                                          String fileName) throws Exception {

        ByteArrayOutputStream out =  new ByteArrayOutputStream();

        try{


            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            OSSObject ossObject = ossClient.getObject(bucketName, fileName);

            InputStream  ossIn = ossObject.getObjectContent();
            /**
             * 为什么不直接返回 ossIn
             * 因为 ossObject.close()后 ossIn也将会关闭
             * 造成其他调用此方法的线程 在使用ossIn的时候
             * 获取到的是一个已经被关闭的流
             * inputStream 应该在调用者线程中关闭
             */

            if(ossIn!=null){
                byte[] bts = new byte[1024];
                int len = -1;
                while((len=ossIn.read(bts))!=-1){
                    out.write(bts,0,len);
                }
            }

            byte[] bytes =  out.toByteArray();

            // 关闭OSSClient。
            ossObject.close();
            ossClient.shutdown();
            return bytes;

        }catch (Exception e){

            e.printStackTrace();
        }finally {
            if(out!=null){
                out.flush();
                out.close();
            }
        }

        return  null;

    }

    /**
     * 以下是byte  和inputStream  互相转换
     * @param buf
     * @return
     */

    public static final InputStream byte2Input(byte[] buf) {
        return new ByteArrayInputStream(buf);
    }

    static void ByteToFile(byte[] bytes)throws Exception{
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        BufferedImage bi1 = ImageIO.read(bais);
        try {
            File w2 = new File("C:\\Users\\cai\\Desktop\\oss2.png");//可以是jpg,png,gif格式
            ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片，此处不需改动
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            bais.close();
        }
    }

    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

        public static void main(String args[]) throws Exception {
//            InputStream inputStream = new FileInputStream("C:\\Users\\cai\\Desktop\\20190818120441.png");
//            getOSS("oss-cn-shanghai.aliyuncs.com",
//                    "LTAI1EpIGd79ERR2",
//                    "jLUwolQ18VznphDo0Uo7LPNFdaL7na",
//                    "genshi",
//                    "2019/8/24/test.jpg");
//            System.out.println("成功上传");
        }




}
